package com.evil.common.config;

import com.cst.executor.ExecutorFactory;
import lombok.Data;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author 阿巳
 */
@Configuration
@Data
public class ThreadPoolConfig {

    private ThreadPoolProperties threadPoolProperties;

    private ThreadPoolExecutor executor;

    private ThreadPoolExecutor executorChild;

    public ThreadPoolConfig(ThreadPoolProperties poolProperties){
        this.threadPoolProperties = poolProperties;

        this.executor = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-service"
        ,poolProperties.getQueueSize()
        ,poolProperties.getCoreThreadNum()
        ,poolProperties.getMaxPoolSize());

        this.executorChild = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-child"
        ,poolProperties.getQueueSize()
        ,poolProperties.getCoreThreadNum()
        ,poolProperties.getMaxPoolSize());
    }

    /**
     * 并发执行任务
     * @param taskList 任务列表
     * @param executors
     * @param <T>
     * @return 返回参数
     */
    public <T> List<T> doTask(List<Callable<T>> taskList ,ThreadPoolExecutor... executors){
        if (taskList == null || taskList.isEmpty()){
            return null;
        }
        List<T> result = new ArrayList<>();
        List<Future<T>> futureList = null;
        try {
            if (executor.getQueue().size() >= threadPoolProperties.getQueueSize()){
                throw new RuntimeException("queue size bigger than 100, now size is " + executor.getQueue().size());
            }
            if (executors != null && executors.length > 0 && executors[0] != null){
                futureList = executors[0].invokeAll(taskList);
            }else {
                futureList = executor.invokeAll(taskList,threadPoolProperties.getTimeOut(), TimeUnit.SECONDS);
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        doFutureList(result, futureList);
        return result;
    }

    private <T> void doFutureList(List<T> result, List<Future<T>> futureList) {
        if (futureList != null){
            for (Future<T> future : futureList) {
                try {
                    result.add(future.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
